<?php

namespace app\admin\controller;

use app\BaseController;
use app\dic\DicCustomer;
use app\dic\DicSite;
use think\facade\Db;
use think\App;

/**
 * @author xjw
 * @class:Taskcustomer 定时任务=>顾客操作
 * @method:customer 获取顾客信息
 * @method:deal_customer 处理顾客信息
 * @method:update_customer_status 更新顾客营销状态
 * @return  
 */

class Taskcustomer extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 
     * type=1 实时的顾客 
     * type=2 之前的顾客
     */

    public function customer()
    {
        $type = input('type');
        $where = array();
        $where['status'] = DicSite::$status_normal;
        $site_id = input('site_id');
        if (!empty($site_id)) {
            $where['id'] = $site_id;
        } else {
            $where[]  = ['id', '>=', 7];
        }
        $result = array();
        if (!empty($type)) {
            $site = table('site')
                ->where('site_type', DicSite::$site_type_1)
                ->where($where)
                ->order('updatetime_customer asc')
                ->find();
            if ($site) {
                $result = $this->deal_customer($site, $type);
                $sitelarr['updatetime_customer'] = time();
                table('site')
                    ->where('id', $site['id'])
                    ->update($sitelarr);
            }
        }
        return success('操作成功', $result);
    }


    public function deal_customer($site, $type)
    {
        date_default_timezone_set('Asia/Shanghai');
        $url = $site['site_url'] . "/admin/api/2021-07/customers.json";
        //获取之前所有的
        if ($type == DicCustomer::$type_2) {
            $limit = '150';
            $before_leads = table('customer')
                ->where('site_id', $site['id'])
                ->order('ycreated_at asc')
                ->find();
            if ($before_leads) {
                $created_at_max = $before_leads['ycreated_at'];
                if (empty($created_at_max)) {
                    date_default_timezone_set('Asia/Shanghai');
                    $created_at_max1 = date('Y-m-d', strtotime("now"));
                    $created_at_max2 = date('H:i:s', strtotime("now"));
                    $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
                } else {
                    $created_at_maxs = explode('T', $created_at_max);
                    $created_at_maxs2 = explode('+', $created_at_maxs[1]);
                    $created_at_maxs3 = strtotime($created_at_maxs[0] . ' ' . $created_at_maxs2[0]) - 8 * 3600;
                    $created_at_max = date('Y-m-d\TH:i:s', $created_at_maxs3) . '+08:00';
                }
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            //拉取之前的订单
            $url = $url . '?created_at_max=' . $created_at_max;
        }
        //实时更新
        if ($type == DicCustomer::$type_1) {
            $limit = '50';
            $customer_info = table('customer')
                ->where('site_id', $site['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($customer_info) {
                $updated_at_min = $customer_info['ycreated_at'];
                if (!empty($updated_at_min)) {
                    $updated_at_mins = explode('T', $updated_at_min);
                    $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                    $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $updated_at_min = '2022-05-01T00:00:00-04:00';
                }
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2022-05-01T00:00:00-04:00';
            }
            $url = $url . '?created_at_min=' . $updated_at_min;
        }
        //更新时间 往前
        if ($type == DicCustomer::$type_3) {
            $limit = '50';
            $before_leads = table('customer')
                ->where('site_id', $site['id'])
                ->where('yupdated_at ','is not null')
                ->order('yupdated_at asc')
                ->find();
            if ($before_leads) {
                $created_at_max = $before_leads['yupdated_at'];
                if (empty($created_at_max)) {
                    date_default_timezone_set('Asia/Shanghai');
                    $created_at_max1 = date('Y-m-d', strtotime("now"));
                    $created_at_max2 = date('H:i:s', strtotime("now"));
                    $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
                } else {
                    $created_at_maxs = explode('T', $created_at_max);
                    $created_at_maxs2 = explode('+', $created_at_maxs[1]);
                    $created_at_maxs3 = strtotime($created_at_maxs[0] . ' ' . $created_at_maxs2[0]) - 8 * 3600;
                    $created_at_max = date('Y-m-d\TH:i:s', $created_at_maxs3) . '+08:00';
                }
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            //拉取之前的订单
            $url = $url . '?updated_at_max=' . $created_at_max;
        }
        //更新时间 实时
        if ($type == DicCustomer::$type_4) {
            $limit = '50';
            $customer_info = table('customer')
                ->where('site_id', $site['id'])
                ->order('yupdated_at desc')
                ->find();
            if ($customer_info) {
                $updated_at_min = $customer_info['yupdated_at'];
                if (!empty($updated_at_min)) {
                    $updated_at_mins = explode('T', $updated_at_min);
                    $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                    $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $updated_at_min = '2024-05-01T00:00:00-04:00';
                }
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $updated_at_min = '2024-05-01T00:00:00-04:00';
            }
            $url = $url . '?updated_at_min=' . $updated_at_min;
        }
        // halt($url);
        if (!empty($type)) {
            $url = $url . '&limit=' . $limit;
            $data =  geturl($url, $site['apikey'], $site['apisecret']);
            $update_ordertime_data_errors = $data;
            $data = json_decode($data, true);
            $result = '';
            if (!empty($data['errors'])) {
                $sitelarr['errors'] = $update_ordertime_data_errors;
                $sitelarr['updatetime_customer'] = time();
                table('site')
                    ->where('id', $site['id'])
                    ->update($sitelarr);
                return $sitelarr['errors'].'错误'.$site['id'];
            }
            if (isset($data['customers'])) {
                if (is_array($data['customers']) && !empty($data['customers'])) {
                    //方案1
                    // halt($data);
                    foreach ($data['customers'] as  $v) {
                        $arr = array();
                        $arr['owner_id'] = 1;
                        if($v['accepts_marketing'] == true){
                            $arr['is_published'] = 1;
                        }else{
                            $arr['is_published'] = 0;
                        }
                        
                        $arr['modified_by'] = 1;
                        $arr['points'] = 0;
                        $arr['preferred_locale'] = 'zh_Hans_SG';
                        $arr['site_id'] = $site['id'];
                        $arr['customer_id'] = $v['id'];
                        $arr['count'] = $v['orders_count'];
                        $arr['tags'] = $v['tags'];
                        $arr['ycreated_at'] = $v['created_at'];
                        $arr['yupdated_at'] = $v['updated_at'];
                        $arr['date_identified'] = date('Y-m-d h:i:s', strtotime($v['updated_at']));
                        if (!empty($v['addresses'])) {
                            if (!empty($v['addresses'][0]['name']) && isset($v['addresses'][0]['name'])) {
                                $arr['title'] = $v['addresses'][0]['name'];
                            }
                            $arr['firstname'] = $v['addresses'][0]['first_name'];
                            $arr['lastname'] = $v['addresses'][0]['last_name'];
                            $arr['company'] = $v['addresses'][0]['company'];
                            $arr['phone'] = $v['addresses'][0]['phone'];
                            $arr['address1'] = $v['addresses'][0]['address1'];
                            $arr['address2'] = $v['addresses'][0]['address2'];
                            $arr['city'] = $v['addresses'][0]['city'];
                            $arr['zipcode'] = $v['addresses'][0]['zip'];
                            $arr['country'] = $v['addresses'][0]['country'];
                        }else{
                            $arr['phone'] = "";
                        }
                        if (empty($arr['phone']) && !empty($v['phone']) && isset($v['phone'])) {
                            $arr['phone'] = $v['phone'];
                        }else{
                            $arr['phone'] = "";
                        }
                        if (!empty($v['email']) && isset($v['email'])) {
                            $arr['email'] = $v['email'];
                        }else{
                            $arr['email'] = "";
                        }
                        $arr['mobile'] = $arr['phone'];
                        $arr['state'] = $v['state'];

                        $row = table('customer')
                            ->where('customer_id', $arr['customer_id'])
                            ->find();
                        if(!empty($row)){
                            // if ($row['yupdated_at'] !== $arr['yupdated_at']) {
                                $arr['date_modified'] = time();
                                $result =  table('customer')->where(['customer_id' => $arr['customer_id']])->update($arr);
                            // } else {
                            //     $result = $result . '重复';
                            // }
                        } else {
                            $arr['date_added'] = date('Y-m-d h:i:s', strtotime($v['created_at']));
                            $result =  table('customer')->insert($arr);
                        }
                    }
                } else {
                    $result = $data;
                }
            }
        }
        return $result;
    }

    /**
     * 
     * 更新顾客营销状态
     */
    public function update_customer_status($id = null)
    {
        $site_id = input('site_id');
        if (!empty($id)) {
            $customers = table('customer')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $where = array();
            $aid = input('aid');
            $bid = input('bid');
            $type = input('type');
            if (!empty($aid) && !empty($bid)) {
                $where['id'] =  ['between', [$aid, $bid]];
            }
            if ($type == 1) {
                $where[] =  ['customers_timea' => ['between', [0, 2]]];
            }
            if ($type == 2) {
                $where['customers_timea'] =  '99999999999';
            }
            if (!empty($site_id)) {
                $where['site_id'] =  $site_id;
            }
            $where['is_published'] = 0;
            $customers = table('customer')
                ->where($where)
                ->where('email', '<>' , "")
                ->order('customers_timea asc,ycreated_at desc')
                ->limit('5')
                ->select()->toarray();
        }
        if (!empty($customers)) {
            $row = array();
            $returns = array();
            $site = table('site')
                ->where('id', $site_id)
                ->find();
            foreach ($customers as $customer) {
                
                $customer_id = $customer['customer_id'];
                $post['customer']['id'] = $customer_id;
                $post['customer']['accepts_marketing'] = true;
                $post['customer']['verified_email'] = true;
                $post['customer']['accepts_marketing_updated_at'] = '2024-06-20T15:32:56-04:00';
                $url2 = $site['site_url'] . "/admin/api/2021-07/customers/" . $customer_id . ".json";
                $data2 =  puturl($url2, $post, $site);
                $data2 = json_decode($data2, true);
                if (isset($data2['errors']) && !empty($data2['errors'])) {
                    $row['customers_timea'] = '99999999999';
                } else {
                    $row['is_published'] = 1;
                    $row['customers_timea'] = time();
                }
                $returns[] = table('customer')
                    ->where('id', $customer['id'])
                    ->update($row);
            }
            return   success('操作成功', $returns);
        } else {
            return  error('未找到相关订单');
        }
    }


    //http://zh.dnssystem.cn/api/Mautic/MauticShopifyCustomers
    //获取顾客订单
    public function MauticShopifyCustomers($id = null)
    {
        if (!empty($id)) {
            $leads =  Db::connect($this->connection)->name('leads')
                ->where('id',$id)
                ->select();
        }else {
            $ids = $this->request->request('ids');
            $where = array();
            if (!empty($ids)) {
                $where['accounturl'] = $ids;
            }else{
                //从56店铺开始更新
                $where['accounturl']  = array('egt',56);
            }
            $leads = Db::connect($this->connection)->name('leads')
                ->order('updatetime_mautic asc')
                ->where($where)
                ->limit('10')
                ->select();
        }
        if (!empty($leads)) {
            $row = array();
            $result = array();
            foreach ($leads as $t) {
                $iscustom = Db::name('fedition_accounturl')
                    ->where('id', $t['accounturl'])
                    ->find();
                $url = $iscustom['shopifyname']."/admin/api/2021-07/customers/".$t['customer_id']."/orders.json";
                $data = $this->geturl($url,$iscustom['shopifyapikey'],$iscustom['shopifysecretapikey']);
                $data = json_decode($data, true);
                if (!empty($data['errors']) || !empty($data['error'])) {
                    $this->success('店铺已下线');
                }
                if (isset($data['orders'])) {
                    if(is_array($data['orders']) && !empty($data['orders'])){
                        //方案1
                        $arr = array();
                        foreach ($data['orders'] as $k => $v) {
                            $arr['accounturl'] = $t['accounturl'];
                            $arr['order_id'] = $v['id'];
                            $arr['customer_id'] = $t['customer_id'];

                            $row = Db::connect($this->connection)->name('leads_order')
                                ->where('order_id',$v['id'])
                                ->find();
                            if($row){
                                $result[] = '重复';
                            }else{
                                $result[] =  Db::connect($this->connection)->name('leads_order')->insert($arr);
                            }
                        }
                    }else{
                        $result[] = $data;
                    }
                }
                $row['updatetime_mautic'] = time();
                Db::connect($this->connection)->name('leads')
                    ->where('id', $t['id'])
                    ->update($row);
            }
            $this->success('操作成功',$result);
        } else {
            $this->error('未找到相关数据');
        }
    }

    /**
     * 转移顾客
     * @param array params
     * 121.5.76.151:100/api/Myshopify/customers_transfer?oldid=80&newid=79
     */
    public function customers_transfer()
    {
        $oldid = $this->request->request('oldid');
        $newid = $this->request->request('newid');
        // if(!empty($oldid) && !empty($newid)){
            
        // }else{
        //     return error('参数错误');
        // }
        $iscustom = Db::name('site')
            ->where('id', $newid)
            ->find();
        if(empty($iscustom)){
            return error('找不到店铺');
        }
        $url = $iscustom['site_url'] . "/admin/api/2023-07/customers.json";
        // $customers_transfer = Db::name('customer_manual')
        //     ->where('transfer_time', 0)
        //     ->limit(20)
        //     ->select();

        $customers_transfer = array();
        if(!empty($oldid)){
            $customers_transfer = Db::name('customer')
            ->where('site_id', $oldid)
            ->where('transfer_time', 0)
            ->limit(20)
            ->select()->toarray();
        }
        $returns = array();
        foreach ($customers_transfer as $k => $v) {
            $row = array();
            $arr = array();
            // $arr['customer']['metafields'][0]['key'] =  'new';
            // $arr['customer']['metafields'][0]['value'] = 'newvalue';
            // $arr['customer']['metafields'][0]['type'] = 'single_line_text_field';
            // $arr['customer']['metafields'][0]['namespace'] = 'global';

            $arr['customer']['addresses'][0]['name'] = $v['title'];
            $arr['customer']['addresses'][0]['first_name'] = $v['firstname'];
            $arr['customer']['addresses'][0]['last_name'] = $v['lastname'];
            $arr['customer']['addresses'][0]['company'] = $v['company'];
            $arr['customer']['addresses'][0]['phone'] = $v['phone'];
            $arr['customer']['addresses'][0]['address1'] = $v['address1'];
            $arr['customer']['addresses'][0]['address2'] = $v['address2'];
            $arr['customer']['addresses'][0]['city'] = $v['city'];
            $arr['customer']['addresses'][0]['zip'] = $v['zipcode'];
            $arr['customer']['country'] = $v['country'];
            $arr['customer']['email'] = $v['email'];
            $arr['customer']['accepts_marketing'] = true;
            $arr['customer']['send_email_invite'] = false;
            $arr['customer']['verified_email'] = false;
            $arr['customer']['first_name'] = $v['firstname'];
            $arr['customer']['last_name'] = $v['lastname'];
            // $arr['customer']['tags'] = 'New Data-US+CA';
            $arr['customer']['tags'] = 'Riceel';
            $data2 = posturl($url, $arr, $iscustom);
            $data = json_decode($data2, true);
            if (isset($data['errors']) && !empty($data['errors'])) {
                $row['errors'] = $data2;
                $row['customers_timea'] = '999';
            }
            $row['transfer_time'] = time();
            $returns[] = Db::name('customer')
                ->where('id', $v['id'])
                ->update($row);
            // $returns[] = Db::name('customer_manual')
            //     ->where('id', $v['id'])
            //     ->update($row);
        }
        return success('操作成功', $returns);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function customers_transfer_oldsystems()
    {
        $customers_transfer = Db::name('leads')
            ->where('dao_old', 0)
            ->order('dao_oldtime asc')
            ->limit(60)
            ->select();
        $returns = array();
        foreach ($customers_transfer as $k => $v) {
            $arr = array();
            $customer = Db::name('customer')
                ->where('customer_id', $v['customer_id'])
                ->find();
            if(empty($customer)){
                $arr['dao_old'] = 1;
                $arr['dao_oldtime'] = time();
                    //导入到customer表
                    $row = array();
                    $row['site_id'] = 0;
                    $fedition_accounturl = Db::name('fedition_accounturl')
                        ->where('id', $v['accounturl'])
                        ->find();
                    if(!empty($fedition_accounturl)){
                        if($fedition_accounturl['iscustom'] == 1){
                            $site = Db::name('site')
                                ->where('site_url', $fedition_accounturl['shopifyname'])
                                ->find();
                            $row['site_id'] = $site['id'];
                        }
                    }
                    if($row['site_id'] == 0){
                        continue;
                    }else{
                        $row['ycreated_at'] = $v['ycreated_at'];
                        $row['customer_id'] = $v['customer_id'];
                        $row['owner_id'] = $v['owner_id'];
                        $row['is_published'] = $v['is_published'];
                        $row['modified_by'] = $v['modified_by'];
                        $row['points'] = $v['points'];
                        $row['preferred_locale'] = $v['preferred_locale'];
                        $row['date_identified'] = $v['date_identified'];
                        $row['title'] = $v['title'];
                        $row['firstname'] = $v['firstname'];
                        $row['lastname'] = $v['lastname'];
                        $row['company'] = $v['company'];
                        $row['phone'] = $v['phone'];
                        $row['address1'] = $v['address1'];
                        $row['address2'] = $v['address2'];
                        $row['city'] = $v['city'];
                        $row['zipcode'] = $v['zipcode'];
                        $row['country'] = $v['country'];
                        $row['email'] = $v['email'];
                        $row['mobile'] = $v['mobile'];
                        $row['state'] = $v['state'];
                        $row['type'] = 2;
                        $returns[] = Db::name('customer')->insert($row);
                    }
                    
            }else{
                $arr['dao_old'] = 2;
                $arr['dao_oldtime'] = time();
            }
            $returns[] = Db::name('leads')
                ->where('id', $v['id'])
                ->update($arr);
        }
        return success('操作成功', $returns);
    }

    
    /**
     * 
     * 更新顾客营销状态
     */
    public function update_customer_tag($id = null)
    {
        if (!empty($id)) {
            $customers = table('customer')
                ->where('id', $id)
                ->select()->toarray();
        } else {
            $where = array();
            $customers = table('customer')
                ->order('tags_time asc')
                ->where($where)
                ->limit('5')
                ->select();
        }
        if (!empty($customers)) {
            $row = array();
            $returns = array();
            foreach ($customers as $customer) {
                $row = array();
                if(!empty($customer['site_id'])){
                    $site = table('site')
                        ->where('id', $customer['site_id'])
                        ->find();
                    $url = $site['site_url'] . "/admin/api/2021-07/customers/" . $customer['customer_id'] . ".json"; 
                    $data =  geturl($url, $site['apikey'], $site['apisecret']);
                    $data = json_decode($data, true);
                    if (isset($data['customer']) && !empty($data['customer'])) {
                        if (isset($data['customer']['tags']) && !empty($data['customer']['tags'])) {
                            $row['tags'] = $data['customer']['tags'];
                        }
                        $row['email'] = $data['customer']['email'];
                        $row['phone'] = $data['customer']['phone'];
                        $row['count'] = $data['customer']['orders_count'];

                        if($data['customer']['accepts_marketing'] == true){
                            $row['is_published'] = 1;
                        }else{
                            $row['is_published'] = 0;
                        }
                    }
                }
                $row['tags_time'] = time();
                $returns[] = table('customer')
                    ->where('id', $customer['id'])
                    ->update($row);
            }
            return success('操作成功', $returns);
        } else {
            return error('未找到相关订单');
        }
    }
    
}
